// import { getInfo } from '@/api/user'
import { clearCookie, setCookie, getCookie, removeCookie, setStore } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes } from '@/router'
import { getJwt } from '@/api/login'
import { permissionMenu, getAuthToken, getUserInfo, getTenantList } from '@/api/userAuth'
import { getTenantList as getTenans } from '@/api/tenant'
import _ from 'lodash'
import { lookForAllId } from '@/views/systemAdmin/roleComponents/index'
import Qs from 'qs'
import { JIEMA_TIMEOUT, JIEMA_USERNAME_PAW } from '@/utils/local'
import { jiemaLogin } from '@/api/jiema'
import Cookies from 'js-cookie'
import initMqtt from "@/views/common/js/device/mqttUtils.js";
import Vue from 'vue'
let TIME = null
function filter(nodes, ids = []) {
  let cloneNodes = _.cloneDeep(nodes);

  let predicate = function (node) {
    if (ids.includes(node.meta.id)) {

      return true;
    } else {
      return false;
    }
  };
  if (!(cloneNodes && cloneNodes.length)) {
    return [];
  }
  let newChildren = [];
  for (let node of cloneNodes) {
    // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
    let subs = filter(node.children, ids);
    if (predicate(node)) {
      newChildren.push(node);
    } else if (subs && subs.length) {
      node.children = subs;
      newChildren.push(node);
    }

  }
  return newChildren.length ? newChildren : [];
}
const getDefaultState = () => {
  return {
    authToken: getCookie('authToken'),//后续删除
    jwt: getCookie('jwt'), //后续删除
    // user: getCookie('user'),
    user: '', //用户信息
    tenant: {},//当前选择的租户
    routes: [],//拥有的路由
    tenantList: [],//拥有的租户
    usernamePassword: '',//账号密码存储--后续获取token使用
    accessToken: '',//全局的jwt令牌
    authTokenInfo: {},//jwt令牌对象-内部包含了刷新使用的token
    jiemaTimeObj: null
  }
}

const state = getDefaultState()
const getters = {
  // 判断当前是否有权限跳转
  isNavTo: state => {
    // id: 当前页面的路由id
    return function (id) {
      let flg;
      for (let i = 0; i < state.routes.length; i++) {
        const item = state.routes[i];
        if (item.children) {
          item.children.forEach(s => {
            if (s.meta && s.meta.id == id) {
              flg = true
            }
          })
        }
      }
      return flg
    }
  },
}
const mutations = {
  setRoles(state, routes) {
    state.routes = constantRoutes.concat(routes)
    // console.log('object :>> ', routes);
  },
  setAuthTokenInfo(state, authTokenInfo) {
    state.authTokenInfo = authTokenInfo
    // setCookie('authTokenInfo', JSON.stringify(authTokenInfo))
  },
  setAccessToken(state, accessToken) {
    // setCookie('accessToken', accessToken)
    state.accessToken = accessToken
  },
  RESET_STATE: (state) => {
    // Object.assign(state, getDefaultState())
    state.user = ''
    state.tenant = {}
    state.routes = []
    state.tenantList = ''
    state.accessToken = ''
    state.authTokenInfo = {}
    // state.usernamePassword = ''
    // usernamePassword: '',//账号密码存储--后续获取token使用
  },
  SET_AUTH_TOKEN: (state, authToken) => {
    state.authToken = authToken
  },
  SET_JWT: (state, jwt) => {
    state.jwt = jwt
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  // 租户详情
  SET_TENANT: (state, tenant) => {
    state.tenant = tenant
  },
  // 保存租户列表
  setTenantList(state, tenantList) {
    state.tenantList = tenantList
  },
  setUsernamePassword(state, usernamePassword) {
    state.usernamePassword = usernamePassword
  },
  clearToken(state) {
    state.user = ""
    state.tenant = {}
    state.routes = []
    state.accessToken = ''
    state.authTokenInfo = {}


  }
}

const actions = {
  // 捷码登录
  async jiemaLogin({ commit }) {
    return new Promise(async (resolve, reject) => {
      const res = await jiemaLogin();
      Cookies.remove('RUBIKSESSIONID')
      Cookies.set("RUBIKSESSIONID", res.data)
      // resolve(true)
      var param = {
        url: process.env.VUE_APP_MQTT_WS_URL + '/mqtt',
      };
      const tenantTopic = `$avic/superlink/iot/app-center/token`;
      const initmqtt = new initMqtt(param);
      const client = initmqtt.connect(async () => {
        console.log("捷码订阅成功,开始订阅主题=>>>>>>>>>>>>>>");
        // const res = await jiemaLogin();
        // Cookies.remove('RUBIKSESSIONID')
        // Cookies.set("RUBIKSESSIONID", res.data)
        client.subscribe(tenantTopic);
        client.on("message", (topic, message) => {
          const token = message.toString()
          Cookies.set("RUBIKSESSIONID", token)
          console.log('捷码订阅===>>message :>> ', token);
        });
        // resolve(true)
      });

    })
  },
  // 刷新token
  async refreshToken({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      const info = {
        grant_type: 'refresh_token',
        refresh_token: state.authTokenInfo.refresh_token
      }
      const authTokenInfo = await getAuthToken(Qs.stringify(info))
      // 存储token信息
      commit('setAuthTokenInfo', authTokenInfo.data)
      // 单独存储token
      commit('setAccessToken', authTokenInfo.data.access_token)

      resolve(authTokenInfo)
    })

    // console.log('authTokenInfo :>> ', authTokenInfo);
  },
  backtenants({ commit }) {
    return new Promise(async (resolve, reject) => {
      window.clearInterval(TIME)
      TIME = null
      console.log('TIME :>> ', TIME);
      commit('clearToken')
      resolve()
    })
  },
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo


    return new Promise(async (resolve, reject) => {
      // 登录的同时 用户密码拿租户列表
      // await dispatch('getTenantList', userInfo)
      // let authToken = btoa(username + ":" + password)
      // 两套鉴权 这里先写死
      // let authToken = btoa("admin" + ":" + 'password')
      // commit('SET_AUTH_TOKEN', authToken)
      // setCookie('authToken', authToken)
      // 存储账号密码
      commit('setUsernamePassword', userInfo)
      resolve()
      // dispatch('getInfo')
      // getJwt().then(response => {
      //   console.log(response, 'jwt')
      //   var jwt = response.headers["x-superlink-jwt"];
      //   commit('SET_JWT', jwt)
      //   setCookie('jwt', jwt)
      //   resolve()
      // }).catch(error => {
      //   removeCookie('authToken')
      //   reject(error)
      // })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response.data
        if (!data) {
          return reject('未查到用户信息, 请重新登录.')
        }
        commit('SET_USER', data)
        // setCookie('user', JSON.stringify(data))

        resolve(data)
      }).catch(error => {
        throw new Error(error)
      })
    })
  },
  // 获取权限菜单
  getPermissionMenu({ commit }, user) {
    return new Promise(async (resolve, reject) => {
      const { perList, userId } = user
      const res = await permissionMenu(userId)
      const { data } = res.data;
      // 取出拥有的菜单id
      const ids = lookForAllId(data || [])
      // 过滤出拥有的菜单
      const routes = filter(asyncRoutes, ids)
      // 添加每一个模块内的权限字段到对应的路由表中
      routes.forEach(item => {
        item.children.forEach(child => {
          perList.forEach(per => {
            if (child.path == per.path) {
              child.meta.perList.push(per)
            }
            // 配方 主工艺 和 详情的权限字段合并
            if (child.path == '/mainList/mainExhibition' && per.path == 'main/list') {
              child.meta.perList.push(per)
            }
            if (child.path == '/mainList/recipeExhibition' && per.path == 'recipe/list') {
              child.meta.perList.push(per)
            }
            // 工艺模板权限字段合并

            if (child.path == '/temDetails/templateDetailEdit' && per.path == '/temDetails/temExhibition') {
              child.meta.perList.push(per)
            }
            if (child.path == 'furnaceTask/list' && per.path == '/receiveTask' && per.name == '生产任务列表') {
              child.meta.perList.push(per)
            }
            if (child.path == '/device/devicePage/devicesdetails' && per.path == '/devicetypedetails' && per.name == '列举命令') {
              child.meta.perList.push(per)
            }
            if (child.path == '/device/devicePage/devicesdetails' && per.path == 'recipe/list' && per.name == '配方列表') {
              child.meta.perList.push(per)
            }
            // 网关类型详情==>网关
            if (child.path == 'networkType/networkTypDetails' && per.path == '/network') {
              child.meta.perList.push(per)
            }
            // 设备列表===>站点详情
            // if (child.path == '/sitename' && per.path == '/device/devicePage/devices' && per.name == '设备列表') {
            //   child.meta.perList.push(per)
            // }
          })
        })

      })
      // { path: '*', redirect: '/404', hidden: true } //404记得添加在最后
      routes.push({ path: 'dashboard', redirect: '/404', hidden: true })
      // 将所拥有的路由路由保存在vuex
      commit('setRoles', routes)
      resolve(routes)

    }).catch(error => {
      throw new Error(error)
    })
  },
  // 保存token信息
  getAuthToken({ commit, state }, info) {
    return new Promise(async (resolve, reject) => {
      const authTokenInfo = await getAuthToken(Qs.stringify(info))
      // 存储token信息
      commit('setAuthTokenInfo', authTokenInfo.data)
      // 单独存储token
      commit('setAccessToken', authTokenInfo.data.access_token)
      resolve(authTokenInfo)
    }).catch(error => {
      throw new Error(error)
    })
  },
  // 保存当前拥有的租户
  getTenantList({ commit }, userInfo) {
    return new Promise(async (resolve, reject) => {
      try {
        let tenant = await getTenantList(userInfo)
        let tenant2 = await getTenans()

        const tenantList = tenant.data.data.tenantList
        const tenantList2 = tenant2.data.results
        // 拼接完整的租户信息
        tenantList.forEach((item, index) => {
          tenantList2.forEach(tenant => {
            if (item.token == tenant.token) {
              Vue.set(tenantList, index, {
                ...item,
                ...tenant
              })
            }
          })
        })
        console.log('最终拼接租户列表 :>> ', tenantList);
        // const tenants = tenant.data.data ? tenant.data.data.tenantList : []
        commit('setTenantList', tenantList)
        resolve({
          username: userInfo.username,
          password: tenant.data.data.password,
        })
      } catch (error) {
        reject(error)
      }
    }).catch(error => {
      throw new Error(error.message)
    })

  },
  // 保存租户信息
  setTenant({ commit }, tenantInof) {
    return new Promise(async (resolve, reject) => {
      console.log('tenantInof :>> ', tenantInof);
      // const res = await getTenant(tenant)
      // const tenantInof = res.data
      commit("SET_TENANT", tenantInof)
      // setCookie("tenant", JSON.stringify(tenantInof))
      resolve(tenantInof)
    }).catch(error => {
      throw new Error(error)
    })
  },

  // user logout
  logout({ commit, state, dispatch }, isClearLocalStorage) {
    return new Promise(async (resolve, reject) => {
      // 参数1标识模块路径和方法名字 参数2 是函数接受的参数 参数3表示当前方法不输入当前模块
      await dispatch("tagsView/delAllViews", {}, { root: true });
      window.clearInterval(TIME)
      clearCookie(isClearLocalStorage)
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  refreshJwt({ commit }) {
    return new Promise((resolve, reject) => {
      getJwt().then(response => {
        console.log("刷新jwt")
        var jwt = response.headers["x-superlink-jwt"];
        commit('SET_JWT', jwt)
        setCookie('jwt', jwt)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

